package edu.odu.cs.sstore.repository;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import edu.odu.cs.sstore.domain.User;

@Repository
public class UserRepositoryImpl implements UserRepository {
	
	@Autowired(required=true)
	private SessionFactory sessionFactory;
 
	public User findById(Long id) {
		return (User) this.sessionFactory.getCurrentSession().createQuery(
			"from User user where user.id=?").setParameter(0, id)
			.uniqueResult();
	}
 
	public User saveOrUpdate(User user) {
		this.sessionFactory.getCurrentSession().saveOrUpdate(user);
		return user;
	}

	public List<User> getAllUsers() {
		return sessionFactory.getCurrentSession().createQuery("from User user order by user.id").list();
	}

	public User findByUserName(String username) {
		return (User) this.sessionFactory.getCurrentSession().createQuery(
				"from User user where lower(user.username)=?").setParameter(0, username.toLowerCase())
				.uniqueResult();
	}
	
	public void deleteUser(User user) {
		this.sessionFactory.getCurrentSession().delete(user);
	}
	
}
